<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="user-card">
          <div class="user-info">
            <el-upload class="avatar-uploader" action="/api/upload/avatar" :headers="uploadHeaders"
              :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" name="file"
              :with-credentials="true">
              <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar">
                <el-icon>
                  <UserFilled />
                </el-icon>
              </el-avatar>
              <div class="avatar-hover">
                <el-icon>
                  <Camera />
                </el-icon>
              </div>
            </el-upload>
            <h2>{{ userInfo.username }}</h2>
            <p class="user-role">{{ userInfo.role }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <h3>{{ userInfo.orderCount || 0 }}</h3>
                <p>订单总数</p>
              </div>
              <div class="stat-item">
                <h3>{{ userInfo.favoriteCount || 0 }}</h3>
                <p>收藏商品</p>
              </div>
              <div class="stat-item">
                <h3>{{ userInfo.reviewCount || 0 }}</h3>
                <p>评价数量</p>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="contact-card">
          <template #header>
            <div class="card-header">
              <span>联系方式</span>
            </div>
          </template>
          <div class="contact-list">
            <div class="contact-item">
              <el-icon>
                <Message />
              </el-icon>
              <span>邮箱：{{ userInfo.email }}</span>
            </div>
            <div class="contact-item">
              <el-icon>
                <Phone />
              </el-icon>
              <span>手机：{{ userInfo.phone }}</span>
            </div>
            <div class="contact-item">
              <el-icon>
                <Location />
              </el-icon>
              <span>地址：{{ userInfo.address }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card class="tab-card">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form :model="userForm" label-width="100px">
                <el-form-item label="用户名">
                  <el-input v-model="userForm.username" disabled />
                </el-form-item>
                <el-form-item label="真实姓名">
                  <el-input v-model="userForm.realName" />
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="userForm.gender">
                    <el-radio :value="'male'">男</el-radio>
                    <el-radio :value="'female'">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="生日">
                  <el-date-picker v-model="userForm.birthday" type="date" />
                </el-form-item>
                <el-form-item label="个人简介">
                  <el-input v-model="userForm.description" type="textarea" :rows="4" placeholder="请输入个人简介" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleUpdateBasic">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="安全设置" name="security">
              <el-form label-width="100px">
                <el-form-item label="修改密码">
                  <el-button type="primary" @click="showPasswordDialog = true">
                    修改密码
                  </el-button>
                  <el-button type="primary" @click="handleShowContactDialog">
                    修改详细信息
                  </el-button>
                </el-form-item>

                <el-form-item label="手机号码">
                  <span>{{ userInfo.phone || '未绑定' }}</span>
                </el-form-item>
                <el-form-item label="电子邮箱">
                  <span>{{ userInfo.email || '未绑定' }}</span>
                </el-form-item>
                <el-form-item label="联系地址">
                  <span>{{ userInfo.address || '未绑定' }}</span>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="订单历史" name="history">
              <el-table :data="borrowHistory" style="width: 100%" v-loading="loading">
                <el-table-column prop="orderNo" label="订单号" min-width="150" show-overflow-tooltip />
                <el-table-column prop="totalAmount" label="订单金额" width="120">
                  <template #default="scope">
                    ¥{{ scope.row.totalAmount }}
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="下单时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="payTime" label="支付时间" width="180">
                  <template #default="scope">
                    {{ scope.row.payTime ? formatDateTime(scope.row.payTime) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getOrderStatusType(scope.row.status)">
                      {{ getOrderStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80" fixed="right">
                  <template #default="scope">
                    <el-button size="small" type="danger" @click="handleCancel(scope.row)"
                      :disabled="scope.row.status !== 1">取消</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination">
                <el-pagination :current-page="borrowParams.page" :page-size="borrowParams.size"
                  :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next"
                  @update:current-page="val => borrowParams.page = val"
                  @update:page-size="val => borrowParams.size = val" @size-change="handleSizeChange"
                  @current-change="handleCurrentChange" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdatePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改联系方式对话框 -->
    <el-dialog v-model="showContactDialog" title="修改联系方式" width="400px">
      <el-form :model="contactForm" :rules="contactRules" ref="contactFormRef" label-width="100px">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="contactForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="contactForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="contactForm.address" placeholder="请输入联系地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showContactDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateContact">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  UserFilled,
  Camera,
  Message,
  Phone,
  Location, User
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 默认头像
const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 上传请求头
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return {
    'Authorization': `Bearer ${token}`
  }
})

// 页面状态
const activeTab = ref('basic')
const showPasswordDialog = ref(false)
const showContactDialog = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 用户信息
const userInfo = ref({})
// 借阅历史数据
const borrowHistory = ref([])
// 借阅记录查询参数
const borrowParams = ref({
  page: 1,
  size: 10,
  userId: null
})

// 数据列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const pageParams = ref({
  page: 1,
  size: 10
})

// 过滤条件
const filters = ref({
  userId: null,
  status: null
})
// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该订单吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.put(`/orders/${row.id}/cancel`)
      ElMessage.success('取消成功')
      fetchUserOrderHistory()
    } catch (error) {
      console.error('取消失败:', error)
      ElMessage.error(error.response?.data?.message || '取消失败')
    }
  })
}

const handleCurrentChange = (val) => {
  pageParams.value.page = val
}

// 获取订单记录列表
const getList = async () => {
  if (!userInfo.value.id) {
    console.warn('用户ID不存在，无法获取订单记录')
    return
  }

  loading.value = true
  try {
    const res = await request.get(`/orders/user/${userInfo.value.id}`, {
      params: {
        ...pageParams.value,
        ...filters.value
      }
    })
    tableData.value = res.data.content || []
    total.value = res.data.totalElements || 0
  } catch (error) {
    console.error('获取订单记录失败:', error)
    ElMessage.error(error.response?.data?.message || '获取订单记录失败')
  }
  loading.value = false
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.warn('用户未登录，无法获取用户信息')
      ElMessage.warning('请先登录')
      return
    }

    console.log('正在获取用户信息')
    const response = await request.get('/users/info')
    console.log('获取用户信息响应:', response)

    if (response.code === 200) {
      userInfo.value = response.data
      // 确保avatar和icon字段统一
      if (response.data.icon && !response.data.avatar) {
        userInfo.value.avatar = response.data.icon
      }
      // 同步表单数据
      userForm.value = {
        username: response.data.username || '',
        realName: response.data.realName || '',
        gender: response.data.gender || 'male',
        birthday: response.data.birthday || '',
        description: response.data.description || ''
      }
      console.log('用户表单数据:', userForm.value)

      // 设置订单记录查询参数中的用户ID
      borrowParams.value.userId = response.data.id
      // 获取用户的订单历史
      fetchUserOrderHistory()
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取用户订单历史（替代借阅历史）
const fetchUserOrderHistory = async () => {
  if (!borrowParams.value.userId) {
    console.warn('用户ID不存在，无法获取订单历史')
    return
  }

  loading.value = true
  try {
    const res = await request.get(`/orders/user/${borrowParams.value.userId}`, {
      params: {
        page: borrowParams.value.page,
        size: borrowParams.value.size
      }
    })

    if (res.code === 200) {
      // 处理返回的订单记录数据
      borrowHistory.value = res.data.content || []
      total.value = res.data.totalElements || 0
    } else {
      console.error('获取订单历史失败:', res)
      ElMessage.error(res.message || '获取订单历史失败')
    }
  } catch (error) {
    console.error('获取订单历史失败:', error)
    ElMessage.error(error.response?.data?.message || '获取订单历史失败')
  } finally {
    loading.value = false
  }
}

// 更新用户信息
const updateUserInfo = async (data) => {
  try {
    console.log('准备更新的用户信息:', data)
    const response = await request.put('/users/info', data)
    if (response.code === 200) {
      ElMessage.success('用户信息更新成功')
      await fetchUserInfo() // 重新获取用户信息
    } else {
      ElMessage.error(response.message || '更新用户信息失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败')
  }
}

// 处理头像上传
const handleAvatarSuccess = async (response) => {
  console.log('头像上传响应:', response)

  if (response.code === 200) {
    console.log('头像上传成功，返回数据:', response.data)
    try {
      // 更新用户头像
      await updateUserInfo({ icon: response.data })
      // 刷新用户信息
      await fetchUserInfo()
      // 发送事件通知其他组件更新用户头像
      window.emitter.emit('user-avatar-updated', response.data)
      // 更新本地存储的用户信息
      const storedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      storedUserInfo.icon = response.data
      localStorage.setItem('userInfo', JSON.stringify(storedUserInfo))

      ElMessage.success('头像上传成功')
    } catch (error) {
      console.error('更新用户头像失败:', error)
      ElMessage.error('头像上传成功，但更新用户信息失败')
    }
  } else {
    console.error('头像上传失败，服务器响应:', response)
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 文件上传前的验证
const beforeAvatarUpload = (file) => {
  console.log('开始上传文件:', file.name, file.type)

  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 检查文件大小（小于2MB）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过2MB!')
    return false
  }

  return true
}

// 在组件挂载时获取用户信息
onMounted(() => {
  console.log('组件挂载，准备获取用户信息')
  const token = localStorage.getItem('token')
  if (token) {
    console.log('从localStorage获取到token:', token)
    fetchUserInfo()
  } else {
    console.warn('未找到token，用户可能未登录')
    ElMessage.warning('请先登录以查看个人信息')
  }
})

// 表单数据
const userForm = ref({
  username: '',
  realName: '',
  gender: 'male',
  birthday: '',
  description: ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const contactForm = ref({
  phone: '',
  email: '',
  address: ''
})

// 表单引用
const passwordFormRef = ref(null)
const contactFormRef = ref(null)

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 4, message: '密码长度不能小于4位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单验证规则
const contactRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入联系地址', trigger: 'blur' }
  ]
}

// 处理基本信息更新
const handleUpdateBasic = async () => {
  const updateData = {
    username: userForm.value.username,
    realName: userForm.value.realName,
    gender: userForm.value.gender,
    birthday: userForm.value.birthday,
    description: userForm.value.description
  }
  await updateUserInfo(updateData)
}

// 处理密码更新
const handleUpdatePassword = async () => {
  try {
    const response = await request.put('/users/password', passwordForm.value)
    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      showPasswordDialog.value = false
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error('密码修改失败')
  }
}

// 处理联系方式更新
const handleUpdateContact = async () => {
  if (!contactFormRef.value) return

  try {
    await contactFormRef.value.validate()
    const response = await request.put('/users/contact-info', contactForm.value)

    if (response.code === 200) {
      ElMessage.success('联系方式更新成功')
      showContactDialog.value = false
      // 刷新用户信息
      await fetchUserInfo()
    } else {
      ElMessage.error(response.message || '联系方式更新失败')
    }
  } catch (error) {
    console.error('更新联系方式失败:', error)
    ElMessage.error('联系方式更新失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  borrowParams.value.size = val
  borrowParams.value.page = 1
  fetchUserOrderHistory()
}


// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  const date = new Date(datetime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 获取借阅状态类型
const getBorrowStatusType = (status) => {
  switch (status) {
    case 1: return 'primary'  // 借阅中
    case 2: return 'success'  // 已归还
    case 3: return 'danger'   // 已逾期
    default: return 'info'
  }
}

// 获取借阅状态文本
const getBorrowStatusText = (status) => {
  switch (status) {
    case 1: return '借阅中'
    case 2: return '已归还'
    case 3: return '已逾期'
    default: return '未知'
  }
}

// 监听标签页变化，当切换到订单历史标签时刷新数据
watch(activeTab, (newVal) => {
  if (newVal === 'history' && userInfo.value.id) {
    fetchUserOrderHistory()
  }
})

// 处理显示联系方式对话框
const handleShowContactDialog = () => {
  contactForm.value = {
    phone: userInfo.value.phone || '',
    email: userInfo.value.email || '',
    address: userInfo.value.address || ''
  }
  showContactDialog.value = true
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.user-card,
.contact-card,
.tab-card {
  margin-bottom: 20px;
}

.user-info {
  text-align: center;
  padding: 20px 0;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-uploader :deep(.el-upload) {
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
}

.avatar-hover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-uploader:hover .avatar-hover {
  opacity: 1;
}

.avatar-hover .el-icon {
  font-size: 24px;
  color: #fff;
}

.user-info h2 {
  margin: 15px 0 5px;
  font-size: 20px;
}

.user-role {
  color: #909399;
  margin-bottom: 20px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.stat-item h3 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
}

.stat-item p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #909399;
}

.contact-list {
  padding: 0 20px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  color: #606266;
}

.contact-item .el-icon {
  font-size: 18px;
  color: #909399;
}

.bind-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.book-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.book-cover {
  width: 60px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.book-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.book-title {
  font-weight: bold;
  color: #303133;
}

.book-meta {
  color: #909399;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>